package cn.com.greatwall.kafka.rest;

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.com.greatwall.common.exception.BadRequestException;
import cn.com.greatwall.kafka.domain.Task;
import cn.com.greatwall.kafka.service.TopicService;
import cn.com.greatwall.kafka.service.TopicTaskService;
import cn.com.greatwall.kafka.service.dto.TaskDto;
import cn.com.greatwall.kafka.service.dto.criteria.TaskQueryCriteria;
import cn.com.greatwall.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author herw
 * @Time 2021-01-20 13:07:31
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "MQ：Kafka任务管理")
@RequestMapping("/api/mq/topic/task")
public class TopicTaskController {
    private final TopicTaskService topicTaskService;
    private final TopicService topicService;
    
    private static final String ENTITY_NAME = "topicTask";
    
    @Log("导出任务")
    @ApiOperation("导出任务")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('task:list')")
    public void download(HttpServletResponse response, TaskQueryCriteria criteria) throws IOException{
        topicTaskService.download(topicTaskService.queryAll(criteria), response);
    }
    
    @Log("查询任务")
    @ApiOperation("查询任务")
    @GetMapping
    @PreAuthorize("@el.check('task:list')")
    public ResponseEntity<Object> query(TaskQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(topicTaskService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    
    @Log("新增任务")
    @ApiOperation("新增任务")
    @PostMapping
    @PreAuthorize("@el.check('task:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Task resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        topicTaskService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    
    @Log("修改任务")
    @ApiOperation("修改任务")
    @PutMapping
    @PreAuthorize("@el.check('task:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Task resources) {
        topicTaskService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除任务")
    @ApiOperation("删除任务")
    @DeleteMapping
    @PreAuthorize("@el.check('task:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        topicTaskService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    
    @Log("审批任务")
    @ApiOperation("审批任务")
    @PutMapping("/approve")
    @PreAuthorize("@el.check('task:edit')")
    public ResponseEntity<Object> approve(@Validated @RequestBody Task resources) {
        try {
            TaskDto task = topicTaskService.findById(resources.getId());
            // 判断topic是否已存在
            if(!topicTaskService.checkTopicTask(task, resources.getClusterIds())) {
                topicTaskService.update(resources);
                
                if(task.getApproved() == 0) {
                    // 如果下面出异常，将异常信息返回给前台
                    JSONObject obj = topicService.encapsulatedObject(task);
                    if(!obj.getBooleanValue("true")) {
                        return new ResponseEntity<>(obj.getString("message"), HttpStatus.OK);
                    }
                    resources.setApproved(1);
                    topicTaskService.update(resources);
                    //发送邮件通知
                }
            }
        } catch (Exception e) {
            log.error("Update task error.", e);
            throw new BadRequestException(e.getMessage());
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    
    @Log("审批任务")
    @ApiOperation("审批任务")
    @PutMapping("/reject")
    @PreAuthorize("@el.check('task:edit')")
    public ResponseEntity<Object> reject(@Validated @RequestBody Task resources) {
        try {
            TaskDto task = topicTaskService.findById(resources.getId());
            task.setApproved(-1);
            topicTaskService.update(resources);
            //发送邮件通知
        } catch (Exception e) {
            log.error("Update task error.", e);
            throw new BadRequestException(e.getMessage());
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}
